#include "triangulation.h"
#include "fstream"

Triangulation::Triangulation(void)
{
}

Triangulation::~Triangulation(void)
{
	release();
}

void Triangulation::release()
{
	int i, n;
	Point2D *p;
	Triangle2D *t;

	while(points.size() > 0)
	{
		n = points.size();
		p = points[n-1];
		points.pop_back();
		delete p;
	}

	while(triangles.size() > 0)
	{
		n = triangles.size();
		t = triangles[n-1];
		triangles.pop_back();
		delete t;
	}
}

int Triangulation::readFromFile(const char *filename)
{
	ifstream f(filename, ios::in);
	int i, numPoint = 0;
	double x, y;
	Point2D *p;

	if(f.is_open())
	{
		f >> numPoint;

		for(i=0; i<numPoint; i++)
		{
			f >> x;
			f >> y;

			p = new Point2D;
			p->x = x;
			p->y = y;

			points.push_back(p);
		}

		f.close();
		return numPoint;
	}

	return 0;
}

void Triangulation::inscreamentalAlgo()
{
	//Phase 1: Find the bounded rectangle of point set
	double l = left(this->points);
	double t = top(this->points);
	double r = right(this->points);
	double b = bottom(this->points);

	Point2D up_left, up_right;
	up_left.x = l;
	up_left.y = t;

	up_right.x = r;
	up_right.y = t;

	//Phase 2: Create super triangle
	/*
			C
		  /\
		 /  \
		/    \
	   A------B
		
	*/
	Point2D A, B, C;
	A.x = l - (r-l)/2;
	A.y = b - 0.1;

	B.x = r + (r-l)/2;
	B.y = A.y;

	Point2D *pC = intersection2D(A, up_left, B, up_right);

	if(pC != NULL)
	{
		C.x = pC->x;
		C.y = pC->y;
		delete pC;

		//Yeah, ABC is the super triangle now.
	}
}